package lab.cadl.lirui.markdown.core.utils

import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.nio.charset.StandardCharsets
import java.security.MessageDigest

fun <R : Any> R.logger(): Lazy<Logger> {
    return lazy {
        LoggerFactory.getLogger(this::class.java)
    }
}

fun hashString(type: String, input: String): String {
    val hexChars = "0123456789ABCDEF"
    val bytes = MessageDigest
            .getInstance(type)
            .digest(input.toByteArray(StandardCharsets.UTF_8))
    val result = StringBuilder(bytes.size * 2)

    bytes.forEach {
        val i = it.toInt()
        result.append(hexChars[i shr 4 and 0x0f])
        result.append(hexChars[i and 0x0f])
    }

    return result.toString()
}

fun calcIndent(s: String): Int {
    return s.map {
        when (it) {
            ' ' -> 1
            '\t' -> 4
            else -> 1
        }
    }.sum()
}

fun trimIndent(s: String, indent: Int): String {
    var index = 0
    var count = 0
    while (count < indent && index < s.length && s[index].isWhitespace()) {
        count += if (s[index] == '\t') { 4 } else { 1 }
        index += 1
    }

    return s.substring(index)
}